<template>
  <div>
    <ess-table
      ref="essTableRef"
      :thead-list="theadList"
      :other-container-box="otherContainerBox"
      :resize-observer-ele="resizeObserverEle"
      :page-num="searchData.pageNum - 1 + 2"
      :total="total"
      :data-list="dataList"
      @handleCurrentChange="handleCurrentChange"
      @handleSizeChange="handleSizeChange"
      @selectionChange="selectionChange"
      @examine="_=>$emit('examine', _)"
      @operationLog="operationLog"
      @abandoned="_=>$emit('abandoned', _)"
      @chooseType="_=>$emit('chooseType', _)"
      @selectionCriteria="_=>$emit('selectionCriteria',_)"
      @entrustInfo="_=>$emit('entrustInfo',_)"
      @submitInfo="_=>$emit('submitInfo',_)"
      @submitReview="_=>$emit('submitReview',_)"
      @make="_=>$emit('make',_)"
    >
      <div slot="left" class="menu-choose">
        <el-radio-group v-model="assignmentParams.type" size="mini">
          <el-radio-button :label="scheduleListID.processingTasks">待跟进</el-radio-button>
          <el-radio-button :label="scheduleListID.allTasks">所有任务</el-radio-button>
          <el-radio-button :label="scheduleListID.historicalTasks">操作历史</el-radio-button>
        </el-radio-group>
        <el-button size="mini" type="success" style="margin-left:5px;" round @click="goNewItemList">新增建品</el-button>
        <configurationTableHead :configuration="configuration" :type="type" @changeHeadList="changeHeadList" @resetTableHeadData="configuration = getTable(null)" />
        <i class="el-icon-refresh" @click="search" />
      </div>
      <slot slot="right" name="right" />
      <template v-slot:mainStatusDec="{scope}">
        <el-tooltip placement="top" effect="light">
          <reasons slot="content" :data="scope.row.rejectReason" />
          <i v-if="tipIsShow(scope.row)" class="el-icon-warning" style="cursor: pointer" />
        </el-tooltip>
        <span :class="{ tip:tipIsShow(scope.row) }">
          {{ scope.row.mainStatusDec }}
        </span>
      </template>
    </ess-table>
  </div>
</template>

<script>
import essTable from '@/components/eTable/eTable.vue'
import configurationTableHead from './configurationTableHead.vue'
import reasons from './reasons'
import { scheduleList, scheduleListID } from '@/views/coi/commonJs/tableHeadList.js'
import { allTasks, processingTasks, historicalTasks, allTasksExport } from '@/api/coi/onlineTaskAPI/sku'
import { createGoodsTypeKind, createGoodsStatus, verifyStatus, constructionStandard, skuType } from '@/views/coi/commonJs/dictionary'
import { stringToArray } from '@/utils/processingData'
import moment from 'moment'

export default {
  name: 'Assignment',
  components: {
    essTable,
    configurationTableHead,
    reasons
  },
  props: {
    type: {
      type: String,
      default: ''
    },
    assignmentParams: {
      type: Object,
      default() {
        return {
          type: 1,
          loading: false,
          queryNum: 0
        }
      }
    }
  },
  data() {
    return {
      otherContainerBox: ['.app-container', '.checkComponent'],
      resizeObserverEle: ['.app-main', '.app-container'],
      scheduleListID, // 列表的标识
      searchData: {}, // 请求参数
      theadList: [], // 表头数据
      configuration: [], // 配置表头
      dataList: [], // 列表展示数据
      total: 0, // 列表总数
      multipleSelection: [], // 勾选中的数据
      // 按钮的控制可操作否
      btnDisabled: {
        abandoned: true, // 废弃
        batchChooseCriteria: true, // 标准
        batchChooseType: true, // 方式
        batchEntrustInfo: true, // 委托信息
        BatchApprove: true
      }
    }
  },
  watch: {
    'assignmentParams.type': {
      deep: true,
      handler() {
        if (this.assignmentParams.type === this.type) {
          // this.$nextTick(this.$refs.essTableRef.setHeight())
          this.$parent.searchData = this.searchData
        }
      }
    },
    multipleSelection: {
      deep: true,
      handler(val) {
        if (Array.isArray(val) && val.length !== 0) {
          if (this.type === scheduleListID.processingTasks) {
            this.btnDisabled.batchChooseCriteria = !val.every(item => item.mainStatus === '800') // 选择建品方式
            this.btnDisabled.batchChooseType = !val.every(item => item.mainStatus === '1000') // 选择建品方式
            this.btnDisabled.batchEntrustInfo = !val.every(item => item.mainStatus === '2000') // 委托信息
            this.btnDisabled.BatchApprove = !val.every(item => item.mainStatus === '4000') // 审核信息
          }
          if (this.type === scheduleListID.allTasks) this.btnDisabled.abandoned = !val.every(item => item.mainStatus < 6021) // 作废按钮
        } else {
          if (this.type === scheduleListID.processingTasks) {
            this.btnDisabled.batchChooseCriteria = true // 标准
            this.btnDisabled.batchChooseType = true // 选择建品方式
            this.btnDisabled.batchEntrustInfo = true // 委托信息
            this.btnDisabled.BatchApprove = true // 审核信息
          }
          if (this.type === scheduleListID.allTasks) this.btnDisabled.abandoned = true
        }
      }
    }
  },
  created() {
    this.initalData()
    this.handleCurrentChange(1)
    this.getTableHeadData()
    if (this.assignmentParams.type === this.type) this.$parent.searchData = this.searchData
  },
  methods: {
    tipIsShow(v) {
      return Boolean(v.subStatus)
    },
    // 码值转换
    filters(value, arr) {
      const newarr = arr.filter(item => item.value === value)
      if (newarr.length) return newarr[0].label
      else return ''
    },
    // 初始化数据
    initalData() {
      const searchData = {
        pageNum: 0,
        pageSize: 10
      }
      this.searchData = searchData
    },
    // 获取表头已经自定义表头编辑的数据
    getTableHeadData() {
      this.filterTable(this.type)
      this.configuration = this.getTable(this.type)
    },
    // 分页器
    handleCurrentChange(val) {
      this.searchData.pageNum = val - 1
      this.queryData()
    },
    handleSizeChange(val) {
      this.searchData.pageSize = val
      this.handleCurrentChange(1)
    },
    selectionChange(val) {
      this.multipleSelection = val
    },
    // 自定义列表
    getTable(type) {
      const scheduleListCopy = JSON.parse(JSON.stringify(scheduleList(this.type)))
      if (!type) return scheduleListCopy
      const localStorage = window.localStorage.getItem(type)
      const configuration = localStorage ? JSON.parse(localStorage) : null
      if (configuration && Array.isArray(configuration)) {
        configuration.forEach(item => {
          const index = scheduleListCopy.findIndex(head => head.value === item.value)
          if (index !== -1) scheduleListCopy[index].show = item.show
        })
      }
      return scheduleListCopy
    },
    filterTable(type) {
      this.theadList = this.getTable(type).filter(item => item.show)
    },
    changeHeadList() {
      this.$refs.essTableRef.clearSelection()
      this.filterTable(this.type)
      this.$refs.essTableRef.tableKey++
    },
    // 处理请提数据
    handleData() {
      const searchData = JSON.parse(JSON.stringify(this.searchData))
      // 创建时间
      if (Array.isArray(searchData.createByDate) && searchData.createByDate.length === 2) {
        searchData.startCreatedTime = searchData.createByDate[0]
        searchData.endCreateTime = searchData.createByDate[1]
      }
      // 更新时间
      if (Array.isArray(searchData.updataByDate) && searchData.updataByDate.length === 2) {
        searchData.startUpdatedTime = searchData.updataByDate[0]
        searchData.endUpdateTime = searchData.updataByDate[1]
      }

      if ('createByVendorNbr6List' in searchData) searchData.createByVendorNbr6List = stringToArray(searchData.createByVendorNbr6List, /[\n\r]/) // 供应商号
      if ('deptNbrList' in searchData) searchData.deptNbrList = stringToArray(searchData.deptNbrList, /[\n\r]/) // 部门
      if ('upcList' in searchData) searchData.upcList = stringToArray(searchData.upcList, /[\n\r]/) // upc
      if ('skuList' in searchData) searchData.skuList = stringToArray(searchData.skuList, /[\n\r]/) // upc(不含检验码)

      if ('updataByDate' in searchData) delete searchData.updataByDate
      if ('createByDate' in searchData) delete searchData.createByDate
      return searchData
    },
    // 请求数据
    async queryData() {
      try {
        this.assignmentParams.loading = true
        this.assignmentParams.queryNum++
        const { result } = await this.sendQueryData(this.handleData())
        if (result) {
          this.total = result.total
          this.dataList = result.data
          this.dataList.forEach((item) => {
            if (item.createdTime) item.createdTime = moment(item.createdTime).format('YYYY-MM-DD HH:mm')
            if (item.updatedTime) item.updatedTime = moment(item.updatedTime).format('YYYY-MM-DD HH:mm')

            if (item.mainStatus) item.mainStatusDec = this.filters(item.mainStatus, createGoodsStatus) // 流程主状态
            if (item.creationWay) item.creationWayDec = this.filters(item.creationWay, createGoodsTypeKind) // 建品方式
            if (typeof item.validateStatus === 'number') item.validateStatusDec = this.filters(item.validateStatus, verifyStatus) // 历史任务的校验状态
            if (item.buildStandard) item.buildStandardDec = this.filters(item.buildStandard, constructionStandard) // 建品标准
            item.skuTypeDec = this.filters(item.skuType, skuType) // 建品标准
          })
        }
      } finally {
        this.assignmentParams.queryNum--
        if (!this.assignmentParams.queryNum) this.assignmentParams.loading = false
      }
    },
    // 请求列表数据
    async sendQueryData(data) {
      console.log(data, '检索')
      if (this.type === scheduleListID.processingTasks) return await processingTasks(data)
      if (this.type === scheduleListID.allTasks) return await allTasks(data)
      if (this.type === scheduleListID.historicalTasks) return await historicalTasks(data)
    },
    search() {
      this.$refs.essTableRef.clearSelection()
      this.handleCurrentChange(1)
    },
    // 请求下载
    async downloadData() {
      try {
        this.assignmentParams.loading = true
        const params = this.handleData()
        console.log(params, '下载')
        const date = moment(new Date()).format('YYYY-MM-DD')
        if (this.type === scheduleListID.allTasks) return await allTasksExport(params, `线上商品建品任务 ${date}`)
      } finally {
        this.assignmentParams.loading = false
      }
    },
    // 重置数据
    reset() {
      this.initalData()
      this.$parent.searchData = this.searchData
      this.search()
    },
    operationLog({ row }) {
      this.$emit('operationLog', row.id)
    },
    goNewItemList() {
      console.log(this.$router)
      this.$router.replace({
        name: 'OnlineNewItemList'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.menu-choose{
  display: flex;
  align-items: center;
  margin-bottom:8px ;
}
.tip{
  color: 	#FF5151;
}
.el-icon-refresh{
  margin-left: 8px;
  font-size: 22px;
  color: #0071CE;
  cursor: pointer;
}
</style>
